﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using System.Data;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.UI.DataTypes;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Member_Create : FormClientTask
    {
        /// <summary>
        /// On Enter press on field Membership ID move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-05-18      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterMemberID(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Identification_Number").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field NRIC/FIN/Passport No move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-05-18      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterIDNo(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("First_Name").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field First Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-05-18      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterFirstName(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("Last_Name").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-05-18      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterLastName(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Gender").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.1    26/03/2013      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterGender(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Mobile_Country_Code").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.1    26/03/2013      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterMobileCountry(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Mobile_Area_Code").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.1    26/03/2013      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterMobileArea(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Mobile_Number").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Mobile move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-05-18      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterMobile(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("Email").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.1    26/03/2013      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterEmail(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("Birthday").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Last Name move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.1    26/03/2013      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterBirthday(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("RE_Membership_Staff").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// This event is fired when any button is pressed in the form so as to trigger custom functions corresponding to buttons like Fetc.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-06-13      DS          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterForm(object sender, KeyEventArgs args)
        {
            try
            {
                if (Control.ModifierKeys != Keys.Shift && args.KeyCode == Keys.F2)
                    MessageBox.Show("U pressed F2", "Bingo...");
                else if (Control.ModifierKeys != Keys.Shift && args.KeyCode == Keys.F3)
                    MessageBox.Show("U pressed F3", "Bingo...");
                else if (Control.ModifierKeys == Keys.Shift && args.KeyCode == Keys.F2)
                    MessageBox.Show("U pressed Shift + F2", "Bingo...");
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Event on click of Trasaction checkbox.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-11      DS          Initial version for Retail.
        /// </history>
        public virtual void OnClickTransitionCard(object sender, EventArgs args)
        {
            try
            {
                if (TypeConvert.ToBoolean((this.PrimaryDataRow["RE_Transition_Card"])))
                {
                    this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;

                    EnableDisableMembershipSource2(false);

                    //Make the Source Transactions segment read only. The fields on the segment should be non mandatory.
                    MandateSourceTransactions(false);

                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Transition_Card_ID")).Focus();
                }
                else
                    //Make the Source Transactions segment enabled. The fields on the segment should be mandatory.
                    MandateSourceTransactions(true);
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Enable or Disable Membership Source 2 fields.
        /// </summary>
        /// <param name="enable">True, indicates the Membership Source 2 fields need to be enabled, else clears the fields, makes them read-only and focus on the source 1.</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-17      DS          Initial version for Retail.
        /// </history>
        private void EnableDisableMembershipSource2(Boolean enable)
        {
            if (enable)
            {
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Required = true;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).ReadOnly = false;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Membership_2_Order_Id")).Required = true;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Focus();
                this.FormControl.GetControlByName("PivotalGroupBox5").Visible = true;
                ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Required = true;
                ((PivotalForeignKey)this.FormControl.GetControlByName("REAuthorizedById")).Required = true;
            }
            else
            {
                this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Required = false;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).ReadOnly = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Membership_2_Order_Id")).Required = false;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No")).Focus();
                this.FormControl.GetControlByName("PivotalGroupBox5").Visible = false;
                ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Required = false;
                ((PivotalForeignKey)this.FormControl.GetControlByName("REAuthorizedById")).Required = false;
            }
            ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Text = string.Empty;
            this.PrimaryDataRow["RE_Authorized_By_Id"] = DBNull.Value;
        }

        /// <summary>
        /// Event on Exit of Membership Source Receipt No1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-11      DS          Initial version for Retail.
        /// </history>
        public virtual void ExitMembershipSrcRcptNo1(object sender, EventArgs args)
        {
            try
            {
                if (this.PrimaryDataRow["RE_Membership_Reciept_No"].ToString().Trim().Length != 0 && 
                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RE_Membership_Reciept_No"]), TypeConvert.ToString(this.PrimaryDataRow["RE_Membership_Reciept_No_2"])))
                {
                    PivotalMessageBox.Show("You can not enter the Receipt Number more than once.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                    EnableDisableMembershipSource2(false);
                    return;
                }
                if (this.PrimaryDataRow["RE_Membership_Reciept_No"] != DBNull.Value && this.PrimaryDataRow["RE_Membership_Reciept_No"].ToString().Trim().Length != 0)
                {
                    //NN 06 April 2012:Issue 107
                    //User should be able to create memeber Only when  Walk-in Type Sales receipt No is specified.
                    using (DataTable orders = Globals.GetDataTable("RE_Orders with Walk-in Customer Type and Receipt No ?",
                                                                new object[] { this.PrimaryDataRow["RE_Membership_Reciept_No"] },
                                                                new string[] { "SFA_order_Id" }))
                    {
                        if (orders != null && orders.Rows.Count == 0)
                        {
                            //Receipt no. is invalid.
                            PivotalMessageBox.Show("No Order found for the Receipt No: " + this.PrimaryDataRow["RE_Membership_Reciept_No"].ToString(),
                                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                            this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                            this.FormControl.GetControlByDataName("RE_Membership_Reciept_No").Focus();
                        }
                        else if (orders != null && orders.Rows.Count > 0)
                        {
                            object sfaOrderId = orders.Rows[0]["SFA_order_Id"];
                            DataTable members = Globals.GetDataTable("RE_Members with Membership Txn1? Or Membership Txn2?", new object[] { sfaOrderId, sfaOrderId },
                                new string[] { "Contact_Id", "First_Name", "Last_Name" });

                            if (members != null && members.Rows.Count > 0)
                            {
                                //Order is already used for another Member.
                                PivotalMessageBox.Show("This Order is earlier used for Member: " + members.Rows[0]["First_Name"].ToString() + " " +
                                    members.Rows[0]["Last_Name"].ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                                this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                                this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                                EnableDisableMembershipSource2(false);
                            }
                            else
                            {
                                //If and Only if the order passes through all the verification, set the Txn 1.
                                this.PrimaryDataRow["RE_Membership_Order_Id"] = sfaOrderId;

                                //Order is valid and not used for any other member. Now check for the qualifying amount.
                                double transactionAmt1 = TypeConvert.ToDouble(Globals.ServerSqlIndex("SFA_Order", "Quote_Total", Id.Create(sfaOrderId)));

                                //Get the currency for the Store.
                                object currency = Globals.ServerSqlIndex("RE_Store", "Currency_Id", Id.Create(this.PrimaryDataRow["RE_Store_Id"]));

                                //Get the Tier Qualifying amount for the Loyalty Program Tier and the currency.
                                DataTable qualifyingAmt = Globals.GetDataTable("RE_Tier_Qualification for Loyalty Program Tier? Currency?", new object[] { this.PrimaryDataRow["RE_Loyalty_Program_Tier_Id"], currency },
                                    new string[] { "Qualifying_Amount" });
                                if (qualifyingAmt != null && qualifyingAmt.Rows.Count > 0)
                                {
                                    if (transactionAmt1 < TypeConvert.ToDouble(qualifyingAmt.Rows[0]["Qualifying_Amount"]))
                                    {
                                        //DS: Custom method PcmDialog is written in Globals and used here.
                                        if (Globals.PcmDialog("The total value of the transaction(s) should be more than the qualifying amount for the program in the " +
                                         "currency of the transaction. Would you like to add another source transaction? \n Selecting \"No\" will result in resetting the source transaction 1.", "Add another source transaction?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            EnableDisableMembershipSource2(true);
                                        }
                                        else
                                        {
                                            this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                                            this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                                            EnableDisableMembershipSource2(false);
                                        }
                                    }
                                    else
                                        EnableDisableMembershipSource2(false);
                                }
                                else
                                {
                                    PivotalMessageBox.Show("Qualifying amount is not set for this Loyalty Program Tier and Currency.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    this.PrimaryDataRow["RE_Membership_Reciept_No"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_Order_Id"] = DBNull.Value;
                    
                    EnableDisableMembershipSource2(false);
                }
            }
            catch(Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Event on Exit of Membership Source Receipt No2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-11      DS          Initial version for Retail.
        /// </history>
        public virtual void ExitMembershipSrcRcptNo2(object sender, EventArgs args)
        {
            try
            {
                if (this.PrimaryDataRow["RE_Membership_Reciept_No_2"].ToString().Trim().Length != 0 &&
                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RE_Membership_Reciept_No"]), TypeConvert.ToString(this.PrimaryDataRow["RE_Membership_Reciept_No_2"])))
                {
                    PivotalMessageBox.Show("You can not enter the Receipt Number more than once.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Focus();
                    return;
                }
                if (this.PrimaryDataRow["RE_Membership_Reciept_No_2"] != DBNull.Value && 
                    !string.IsNullOrWhiteSpace(TypeConvert.ToString(this.PrimaryDataRow["RE_Membership_Reciept_No_2"])))
                {
                    //Check for the existence of the receipt no in the SFA_Order table.
                    object sfaOrderId = this.PrimaryDataRow["RE_Membership_Order_Id"];
                    //NN 06 April 2012:Issue 107
                    //User should be able to create memeber Only when  Walk-in Type Sales receipt No is specified.
                    using (DataTable orders = Globals.GetDataTable("RE_Orders with Walk-in Customer Type and Receipt No ?",
                                                               new object[] { this.PrimaryDataRow["RE_Membership_Reciept_No_2"] },
                                                               new string[] { "SFA_order_Id" }))
                    {
                        if (orders != null && orders.Rows.Count == 0)
                        {
                            //Receipt no. is invalid.
                            PivotalMessageBox.Show("No Order found for the Receipt No: " + this.PrimaryDataRow["RE_Membership_Reciept_No_2"].ToString(),
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                            this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                            this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2").Focus();
                        }
                        else
                        {
                            Id sfaOrderId2 = Id.Create(orders.Rows[0]["SFA_Order_Id"]);
                            DataTable members = Globals.GetDataTable("RE_Members with Membership Txn1? Or Membership Txn2?",
                                                                        new object[] { TypeConvert.ToDBValue(sfaOrderId2), TypeConvert.ToDBValue(sfaOrderId2) },
                                                                        new string[] { "Contact_Id", "First_Name", "Last_Name" });

                            if (members != null && members.Rows.Count > 0)
                            {
                                //Order is already used for another Member.
                                PivotalMessageBox.Show("This Order is earlier used for Member: " + members.Rows[0]["First_Name"].ToString() + " " +
                                    members.Rows[0]["Last_Name"].ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                                this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                                this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Focus();
                            }
                            else
                            {
                                //Order is valid and not used for any other member. Now check for the qualifying amount.
                                double transactionAmt1 = TypeConvert.ToDouble(Globals.ServerSqlIndex("SFA_Order", "Quote_Total", Id.Create(sfaOrderId)));
                                double transactionAmt2 = TypeConvert.ToDouble(Globals.ServerSqlIndex("SFA_Order", "Quote_Total", sfaOrderId2));

                                //Get the currency for the Store.
                                object currency = Globals.ServerSqlIndex("RE_Store", "Currency_Id", Id.Create(this.PrimaryDataRow["RE_Store_Id"]));

                                //Get the Tier Qualifying amount for the Loyalty Program Tier and the currency.
                                DataTable qualifyingAmt = Globals.GetDataTable("RE_Tier_Qualification for Loyalty Program Tier? Currency?", new object[] { this.PrimaryDataRow["RE_Loyalty_Program_Tier_Id"], currency },
                                    new string[] { "Qualifying_Amount" });
                                if (qualifyingAmt != null && qualifyingAmt.Rows.Count > 0)
                                {
                                    if ((transactionAmt1 + transactionAmt2) < TypeConvert.ToDouble(qualifyingAmt.Rows[0]["Qualifying_Amount"]))
                                    {
                                        PivotalMessageBox.Show("The total value of the transaction(s) should be more than the qualifying amount for the program in the currency of the transaction.",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                                        this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                                        this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2").Focus();
                                    }
                                    else
                                    {
                                        //If and Only if the order passes through all the verification, set the Txn 2.
                                        this.PrimaryDataRow["RE_Membership_2_Order_Id"] = TypeConvert.ToDBValue(sfaOrderId2);
                                    }
                                }
                                else
                                {
                                    PivotalMessageBox.Show("Qualifying amount is not set for this Loyalty Program Tier and Currency.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    this.PrimaryDataRow["RE_Membership_Reciept_No_2"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Membership_2_Order_Id"] = DBNull.Value;
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Makes the source transaction fields read-only depending on the param.
        /// </summary>
        /// <param name="mandate">True, makes the source transaction fields read-only.</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-17      DS          Initial version for Retail.
        /// </history>
        private void MandateSourceTransactions(bool mandate)
        {
            ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No")).ReadOnly = !mandate;
            ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No")).Required = mandate;
            ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Membership_Order_Id")).Required = mandate;
            this.FormControl.GetControlByName("PivotalGroupBox4").Visible = mandate;
            this.FormControl.GetControlByName("PivotalGroupBox5").Visible = !mandate;
            ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Required = !mandate;
            ((PivotalForeignKey)this.FormControl.GetControlByName("REAuthorizedById")).Required = !mandate;
            if (!mandate && this.FormView.Dirty)
            {
                ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Text = string.Empty;
                this.PrimaryDataRow["RE_Authorized_By_Id"] = DBNull.Value;
            }
        }
        
        /// <summary>
        /// On change of Sale Rep Code field on enter key hit or tab out
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.9.1    13-12-2011  DS      Initial Version
        /// </history>
        public virtual void StaffCode_DataSourceUpdated(PivotalControl sender, EventArgs args)
        {
            try
            {
                staffId = null;
                string staffCode = this.FormControl.GetControlByName("txtStaffCode").WindowsControl.Text;
                if (!string.IsNullOrWhiteSpace(staffCode))
                {
                    // lookup for keyed in StaffCode n corresponding Staff_Id
                    DataTable staff = Globals.GetDataTable("RE_Active Staff with Staff Code?", new object[] { staffCode }, "RE_Staff_Id");

                    if (staff != null && staff.Rows.Count == 1)
                    {
                        DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today with Can Authorize and Store?", new object[] { this.PrimaryDataRow["RE_Store_Id"] },
                            "Staff_Id", "Out_Time" );

                        int staffCount = staffLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]) == Id.Create(staff.Rows[0]["RE_Staff_Id"])
                            && Convert.IsDBNull(a["Out_Time"]));

                        if (staffCount > 0)
                        {
                            this.PrimaryDataRow["RE_Authorized_By_Id"] = staff.Rows[0]["RE_Staff_Id"];
                            staffId = Id.Create(staff.Rows[0]["RE_Staff_Id"]);
                            return;
                        }
                        else
                            PivotalMessageBox.Show("Staff is either not logged into the Store or does not have necessary permission to Authorize.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else if (staff != null && staff.Rows.Count > 1)
                        PivotalMessageBox.Show("Multiple Staff records are found for the code entered. Please contact the Administrator.", MessageBoxButtons.OK, 
                            MessageBoxIcon.Stop);
                    else
                        PivotalMessageBox.Show("No Staff record found for the keyed in Sales Rep Code.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    this.FormControl.GetControlByName("txtStaffCode").WindowsControl.Text = string.Empty;
                    this.PrimaryDataRow["RE_Authorized_By_Id"] = DBNull.Value;
                }
                else
                {
                    this.PrimaryDataRow["RE_Authorized_By_Id"] = DBNull.Value;
                    this.FormControl.GetControlByName("txtStaffCode").WindowsControl.Text = string.Empty;
                }

                this.FormControl.GetControlByName("txtStaffCode").Focus();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }
    }
}
